#include "robotlistform.h"
#include "MessageBox.h"
#include "datamanager/datamanagedialog.h"
#include "touchbutton.h"
#include "ui_robotlistform.h"
#include "models/robotlist.h"
#include <QPainter>
#include <QScroller>
#include<QScrollBar>
#include <QPropertyAnimation>
#include <QLabel>
#include "models/operatelogmodel.h"
RobotICONDelegate::RobotICONDelegate(QObject *parent): QStyledItemDelegate(parent) {}

void RobotICONDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // 保存画笔状态
    painter->save();
    //绘制图标
     QIcon icon;
     if (option.state & QStyle::State_Selected){
         icon = QIcon(":/images/robot_ico_select.png");
     } else {
         icon = QIcon(":/images/robot_ico.png");
     }
     icon.paint(painter,option.rect);
     //绘制文字
     QFont f("微软雅黑");
     f.setPixelSize(int(24*g_xScale));
     painter->setFont(f);
     QRect rcText=option.rect.adjusted(int(34*g_xScale),0,int(-34*g_xScale),int(-30*g_xScale));
     QString text = index.data(RobotList::NameRole).toString();
     QString elidedText = painter->fontMetrics().elidedText(text, Qt::ElideRight, rcText.width());
     painter->drawText(rcText, Qt::AlignHCenter | Qt::AlignBottom, elidedText);
    // 恢复画笔状态
    painter->restore();
}

QSize RobotICONDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option)
    Q_UNUSED(index)
    return QSize(int(234*g_xScale), int(264*g_yScale));
}


RobotListForm::RobotListForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RobotListForm)
{
    setAttribute(Qt::WA_StyledBackground, true);
    ui->setupUi(this);
    ui->robot_list->setModel(RobotList::getInstance());
    ui->robot_list->setItemDelegate(new RobotICONDelegate(this));
    ui->robot_list->setHorizontalScrollMode(QListView::ScrollPerPixel);
    ui->robot_list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  // 隐藏水平滚动条
    ui->robot_list->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);    // 隐藏垂直滚动条
    QScroller *scroller = QScroller::scroller(ui->robot_list);
    QScrollerProperties properties = scroller->scrollerProperties();
    properties.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QScrollerProperties::OvershootAlwaysOff);
    scroller->setScrollerProperties(properties);
    QScroller::grabGesture(ui->robot_list, QScroller::LeftMouseButtonGesture);

    // 监听滚动位置变化
    connect(ui->robot_list->horizontalScrollBar(), &QScrollBar::valueChanged, this, [this](int value) {
        // 当滚动到最左边时隐藏pre_page_btn
        ui->pre_page_btn->setVisible(value > 0);
        // 当滚动到最右边时隐藏next_page_btn
        int maxScroll = ui->robot_list->horizontalScrollBar()->maximum();
        ui->next_page_btn->setVisible(value < maxScroll);
    });

    connect(RobotList::getInstance(),&RobotList::rowsRemoved,this,[&](){
        ui->pre_page_btn->setVisible(ui->robot_list->horizontalScrollBar()->value()> 0);
        ui->next_page_btn->setVisible(ui->robot_list->horizontalScrollBar()->value()<ui->robot_list->horizontalScrollBar()->maximum());
    });
    connect(RobotList::getInstance(),&RobotList::rowsInserted,this,[&](){
        ui->pre_page_btn->setVisible(ui->robot_list->horizontalScrollBar()->value()> 0);
        ui->next_page_btn->setVisible(ui->robot_list->horizontalScrollBar()->value()<ui->robot_list->horizontalScrollBar()->maximum());
    });

    // 添加翻页按钮的点击处理
    connect(ui->pre_page_btn, &QPushButton::clicked, this, [this]() {
        // 获取当前视口宽度作为滚动距离
        int scrollWidth = ui->robot_list->viewport()->width();
        // 获取当前滚动位置
        int currentPos = ui->robot_list->horizontalScrollBar()->value();
        // 创建动画
        QPropertyAnimation* animation = new QPropertyAnimation(ui->robot_list->horizontalScrollBar(), "value");
        animation->setDuration(300);  // 300毫秒的动画时长
        animation->setStartValue(currentPos);
        animation->setEndValue(currentPos - scrollWidth);
        animation->setEasingCurve(QEasingCurve::OutCubic);  // 使用缓出曲线
        // 动画结束后自动删除
        connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater);
        animation->start();
    });

    connect(ui->next_page_btn, &QPushButton::clicked, this, [this]() {
        // 获取当前视口宽度作为滚动距离
        int scrollWidth = ui->robot_list->viewport()->width();
        // 获取当前滚动位置
        int currentPos = ui->robot_list->horizontalScrollBar()->value();
        // 创建动画
        QPropertyAnimation* animation = new QPropertyAnimation(ui->robot_list->horizontalScrollBar(), "value");
        animation->setDuration(300);  // 300毫秒的动画时长
        animation->setStartValue(currentPos);
        animation->setEndValue(currentPos + scrollWidth);
        animation->setEasingCurve(QEasingCurve::OutCubic);  // 使用缓出曲线
        // 动画结束后自动删除
        connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater);
        animation->start();
    });
    scaleWidgets(this,g_xScale,g_yScale);
}

void RobotListForm::scaleWidgets(QWidget *widget, double xScale, double yScale)
{
    setFixedSize(int(widget->width() * xScale), int(widget->height() * yScale));
    ui->tittle_widget->setFixedSize(int(ui->tittle_widget->width() * xScale), int(ui->tittle_widget->height() * yScale));
    for (QWidget *child : widget->findChildren<QWidget*>()) {
        if( qobject_cast<QLabel*>(child) ||
            qobject_cast<TouchButton*>(child) ||
            qobject_cast<QFrame*>(child) ||
            qobject_cast<QListView*>(child))
        {
            QRect geom = child->geometry();
            int width = qMax(1, static_cast<int>(int(geom.width() * xScale)));
            //当按钮高度比较大时使用y方向比例，当按钮比较小时使用x比例，防止按钮被压扁
            int height = qMax(1, static_cast<int>((geom.height() == geom.width() ? int(geom.height() * xScale) : int(geom.height() * yScale))));
            child->setFixedSize(width,height);
            child->move(int(geom.left() * xScale),int(geom.top() * yScale));
            QFont font = child->font();
            if(font.pixelSize()> 0)
                font.setPixelSize(int(font.pixelSize()*xScale));
            else if(font.pointSize()> 0)
                font.setPixelSize(int(font.pointSize()*xScale));
            child->setFont(font);
        }
    }
}

RobotListForm::~RobotListForm()
{
    delete ui;
}

void RobotListForm::on_Exit_pushButton_clicked()
{
    if(question(this,tr("确定要退出程序吗？")) == 0)
        qApp->exit(0);
}

void RobotListForm::on_enter_ctrl_btn_clicked()
{
    Robot* pRobot=RobotList::getInstance()->getRobotByIndex(ui->robot_list->currentIndex().row());
    if(pRobot)
    {
        pRobot->connectRobot();
        OPERATE_LOG("连接机器人："+pRobot->strName());
    }
    else{
        warning(this,tr("请选择机器人！"));
    }
}


void RobotListForm::on_data_btn_clicked()
{
    DataManageDialog dlg(this);
    dlg.exec();
}

void RobotListForm::setVisible(bool visible)
{
    QWidget::setVisible(visible);
    if(visible)
    {
        ui->pre_page_btn->setVisible(ui->robot_list->horizontalScrollBar()->value()> 0);
        ui->next_page_btn->setVisible(ui->robot_list->horizontalScrollBar()->value()<ui->robot_list->horizontalScrollBar()->maximum());
    }
}

void RobotListForm::on_back_pushButton_clicked()
{
    emit goback();
}

